package com.buaa.student.post.MyList;

import com.alibaba.fastjson.JSON;

import com.buaa.student.post.to.Lists;
import com.buaa.student.post.to.ResponseStuTo;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.sql.Date;
import java.util.List;
import java.util.stream.Collectors;

public class StepOneUtils {
    public List<Lists> getList() throws Exception {

        //eaiValue是登录成功之后的凭证
        CloseableHttpClient httpClient = addCookieHttpClient("ugmhg5iooruhuaijdkin3fho51");

        //"https://app.buaa.edu.cn/buaaxsncov/wap/datacube-base/ulists?date=2021-05-15&type=weishangbao&page=1&page_size=2000&group_id=1&group_type=1&keywords=";
        //创建URLBuilder
        URIBuilder uriBuilder = new URIBuilder("https://app.buaa.edu.cn/buaaxsncov/wap/datacube-base/ulists");
        //设置参数1，日期为今日的日期
        uriBuilder.setParameter("date", new Date(System.currentTimeMillis()).toString());
        //设置参数2，type为weishangbao
        uriBuilder.setParameter("type", "weishangbao");
        //设置参数3和4，在一页中把所有名单都获取过来
        uriBuilder.setParameter("page", "1");
        uriBuilder.setParameter("page_size", "2000");
        //设置参数4、5和6，设置一下就行，不用搭理
        uriBuilder.setParameter("group_id", "1");
        uriBuilder.setParameter("roup_type", "1");
        uriBuilder.setParameter("keywords", "");

        //2.创建HttpGet对象，设置URL地址
        URI uri = uriBuilder.build();
        HttpGet httpGet = new HttpGet(uri);

        //3.防止被后台识破是机器，伪装成浏览器
        httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36");
        httpGet.addHeader("Referer", "https://app.buaa.edu.cn/site/epideStatebuaaStu/epideType?type=weishangbao&date=2021-05-14&group_id=1&group_type=1");

        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                //响应成功
                String content = EntityUtils.toString(response.getEntity(), "utf8");

                ResponseStuTo responseStuTo = JSON.parseObject(content, ResponseStuTo.class);
                List<Lists> lists = responseStuTo.getD().getLists();
                return filterLists(lists);
            } else {
                System.out.println("响应失败，响应码为:" + response.getStatusLine().getStatusCode());
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 对未打卡的同学的名单进行过滤，过滤掉非本年级的同学的名单。
     *
     * @param lists
     * @return
     */
    private List<Lists> filterLists(List<Lists> lists) {

        //2019级硕士的学号范围在 101 - 918， 再加三个特殊：SY1806516 SY1806603 ZY1806715
        List<Lists> targetList = lists.stream().filter(list -> {
            int num = Integer.parseInt(list.getXgh().substring(2));
            if (num >= 1906101 && num <= 1906918) {
                return true;
            }
            return list.getXgh().equals("SY1806516") || list.getXgh().equals("SY1806603") || list.getXgh().equals("ZY1806715");

        }).collect(Collectors.toList());

        return targetList;
    }

    /**
     * 返回包含必备的Cookie值的HttpClient
     *
     * @param eaiValue 已登录状态的凭证
     * @return
     */
    private CloseableHttpClient addCookieHttpClient(String eaiValue) {

        BasicCookieStore cookieStore = new BasicCookieStore();

        //设置eai-sess
        BasicClientCookie cookieEai = new BasicClientCookie("eai-sess", eaiValue);
        cookieEai.setVersion(0);
        cookieEai.setDomain("app.buaa.edu.cn");
        cookieEai.setPath("/");
        cookieStore.addCookie(cookieEai);

        //设置UUkey
        BasicClientCookie cookieUUkey = new BasicClientCookie("UUkey", "6d9f8a1dd6e0322c86e22b8ab6a8df3c");
        cookieUUkey.setVersion(0);
        cookieUUkey.setDomain("app.buaa.edu.cn");
        cookieUUkey.setPath("/");
        cookieStore.addCookie(cookieUUkey);

        //设置xxbh21.8
        BasicClientCookie cookieXxbh = new BasicClientCookie("xxbh21.8", "94424103");
        cookieXxbh.setVersion(0);
        cookieXxbh.setDomain("app.buaa.edu.cn");
        cookieXxbh.setPath("/");
        cookieStore.addCookie(cookieXxbh);

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

        return httpClientBuilder.setDefaultCookieStore(cookieStore).build();
    }
}
